

import { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
//配置 CustomParseFormat 插件 字符串 + 格式
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)



//  **参数**
//  getTimeDistance('week')
//  - `type` 快捷类型，带 `-` 表示过去一个时间，若指定 `number` 表示天数
//    - `today`、`-today` 今天或昨天
//    - `week`、`-week` 本周或上周
//    - `month`、`-month` 本月或上月
//    - `year`、`-year` 今年或去年
//  - `time` 指定开始时间，默认为：`now`

/**
 * Get the time range, return `[ Date, Date]` for the start and end dates
 *
 * 获取时间范围
 *
 * @param type 类型，带 `-` 表示过去一个时间，若指定 `number` 表示天数
 * @param time 开始时间
 */

export function getTimeDistance(
    type: 'today' | '-today' | 'yesterday' | 'week' | '-week' | 'month' | '-month' | 'year' | '-year' | number,
    time?: Date | string | number
): [Dayjs, Dayjs] {

    let timeClone = time
        ? typeof time === 'string'
            ? dayjs(time, ["YYYY", "YYYY-MM-DD", "yyyy-MM-dd HH:mm:ss"], 'es', true)
            : dayjs(time)
        : dayjs(new Date());
    const options: { weekStartsOn: 1 } = { weekStartsOn: 1 };
    let res: [Dayjs, Dayjs];
    switch (type) {
        case 'today':
            res = [timeClone, timeClone];
            break;
        case '-today':
            res = [timeClone.subtract(1, 'day'), timeClone];
            break;
        case 'yesterday':
            res = [timeClone.subtract(1, 'day'), timeClone.subtract(1, 'day')];
            break;
        case 'week':
            res = [timeClone.startOf('week'), timeClone.endOf('week')];
            break;
        case '-week':
            res = [timeClone.subtract(1, 'week').startOf('week'), timeClone.subtract(1, 'week').endOf('week')];
            break;
        case 'month':
            res = [timeClone.startOf('month'), timeClone.endOf('month')];
            break;
        case '-month':
            res = [timeClone.subtract(1, 'month').startOf('month'), timeClone.subtract(1, 'month').endOf('month')];
            break;
        case 'year':
            res = [timeClone.startOf('year'), timeClone.endOf('year')];
            break;
        case '-year':
            res = [timeClone.subtract(1, 'year').startOf('year'), timeClone.subtract(1, 'year').endOf('year')];
            break;
        default:
            res = type > 0 ? [timeClone, timeClone.add(type, 'day')] : [timeClone.subtract(type, 'day'), timeClone];
            break;
    }
    return res
}

